<script setup>
import { onMounted, ref } from 'vue'
import DrawEcharts from '@/components/draw-echarts.vue'
import icon_house from '@/assets/imgs/ic_fwzs.png'
import {
    getInfrastructureInvestment,
    getEnterpriseStructure,
    getEnterpriseOutputValue,
    getEnterpriseInfoTotal,
    getEnterpriseScale
} from './api.js'

const investRateChartBarRef = ref(null)
const investInfoList = ref([
    {
        title: '累计上架',
        value: '0',
        unit: '个',
        icon: icon_house
    },
    {
        title: '总投资',
        value: '0',
        unit: '亿',
        icon: icon_house
    },
    {
        title: '计划投资',
        value: '0',
        unit: '亿',
        icon: icon_house
    }
])

const getChartPieOption = ({ list, image }) => {
  const total = list.reduce((a, b) => a + b.value, 0)
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{b} <br/> {c} ({d}%)'
    },
    legend: {
      show: false,
      orient: 'vertical',
      top: 'middle',
      left: '65%',
      data: list.map(item => item.name),
      itemWidth: 10,
      itemHeight: 10,
      icon: 'circle',
      itemGap: 10,
      textStyle: {
        color: '#fff',
        fontSize: 12
      },
      formatter: (name) => {
        const value = list.find(item => item.name === name).value
        const per = parseFloat((value / total * 100).toFixed(2))
        return name + '  ' + value + '  ' + per + '%'
      }
    },
    series: [
      {
        name: '',
        type: 'pie',
        radius: ['60%', '78%'],
        center: ['50%', '50%'],
        padAngle: 3, // 轻微的角度间隙
        labelLine: {
          length: 5
        },
        inverse: true,
        label: {
            show: false,
          formatter: '{b|{b}}\n{hr|}\n{per|{d}%}  ',
          rich: {
            b: {
              color: '#ffffff',
              fontSize: 14,
            },
            hr: {
              borderColor: '#8C8D8E',
              width: '100%',
              borderWidth: 1,
              height: 0
            },
            c: {
              color: '#ffffff',
              fontSize: 14,
              lineHeight: 28
            },
            unit: {
              color: '#ccc',
              fontWeight: 'normal',
            },
            per: {
              color: '#ffffff',
              lineHeight: 28
              // backgroundColor: '#4C5058',
              // padding: [3, 4],
              // borderRadius: 4
            }
          }
        },
        data: list,
      }
    ],
    // 添加 graphic 组件显示图片
    graphic: {
      elements: [{
        type: 'image',
        key: 'centerImage',
        z: 100,
        style: {
          image: image, // 你的图片路径
          width: 140,
          height: 140
        },
        left: '25%',
        top: 'center'
      }]
    },
    backgroundColor: 'transparent',
  }
}

const barColors = [
{
    type: 'linear',
    x: 0,
    y: 0,
    x2: 0,
    y2: 1,
    colorStops: [{
        offset: 0, color: '#FFE676' // 0% 处的颜色
    }, {
        offset: 1, color: '#FF933A' // 100% 处的颜色
    }],
    global: false // 缺省为 false
    },
    {
    type: 'linear',
    x: 0,
    y: 0,
    x2: 0,
    y2: 1,
    colorStops: [{
        offset: 0, color: '#CBFBFF' // 0% 处的颜色
    }, {
        offset: 1, color: '#02AAFA' // 100% 处的颜色
    }],
    global: false // 缺省为 false
    }
]
const getChartBarOption = (data) => {

  return {
    backgroundColor: 'transparent',
    tooltip: {
       trigger: 'axis',
        axisPointer: {
            type: 'shadow'
        }
    },
    legend: {
      top: 'top',
      right: '14%',
      itemWidth: 10,
      itemHeight: 10,
      itemGap: 30,
    },
    grid: {
      left: '12%',
      right: '12%',
      top: '23%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.xAxis,
    },
    yAxis: {
      type: 'value'
    },
    series: data.series.map((item,i)=> {
        return {
            name: item.name,
            type: 'bar',
            itemStyle: {
                color: barColors[item.colorIndex]
            },
            emphasis: {
                focus: 'series'
            },
            data: item.data, // [320, 302, 301, 334, 390, 330, 320]
        }
    })
  }
}

const updateDataInvestRate = (data) => {
    investInfoList.value[0].value = data['累计上架']
    investInfoList.value[1].value = data['总投资']
    investInfoList.value[2].value = data['计划投资']
    investRateChartBarRef.value?.updateOption(getChartBarOption({
        xAxis: data.xAxis, // ['一季度', '二季度', '三季度', '四季度'],
        series: [
            {
                name: data.legend[0] + '年',
                colorIndex: 1,
                data: data.data1,
            },
            {
                name: data.legend[1] + '年',
                colorIndex: 2,
                data: data.data2,
            }
        ]
    }))
}
const registeredBuildingEnterpriseStructureChartRef = ref()
const enterpriseCountList = ref([])
const updateDataEnterpriseCount = (data) => {
    const colors = ['#0380F5', '#FFE552', '#44FF9D', '#7575FF']
    const list = Object.entries(data).map(([key, value], i) => ({
        name: key, value, itemStyle: { color: colors[i] }
    }))
    enterpriseCountList.value = list
    registeredBuildingEnterpriseStructureChartRef.value?.updateOption(getChartPieOption({ list, image: icon_house }))
}

const enterpriseValueChartBarRef = ref()
const updateDataEnterpriseValue = (data) => {
    const res = {
        xAxis: data.xAxis, // ['一季度', '二季度', '三季度', '四季度'],
        series: [
            {
                name: data.legend[0] + '年',
                colorIndex: 0,
                data: data.data1,
            },
            {
                name: data.legend[1] + '年',
                colorIndex: 1,
                data: data.data2,
            }
        ]
    }
    enterpriseValueChartBarRef.value?.updateOption(getChartBarOption(res))
}

const totalList = ref([])
const unitObj = {
    '在建项目': '个', '在建房屋项目':'个', '在建房屋项目总面积': '万平', '本年度房屋竣工面积':'万平',
    '在建市政项目': '个','在建市政项目总造价': '亿','本年度已完成投资': '亿','本年度签到合同金额': '亿'
}   
const updateTotalInfo = (data) => {
    totalList.value =  Object.entries(data).map(item => {
        return {
            title: item[0],
            value: item[1],
            unit: unitObj[item[0]]
        }
    })
}

const isLoading = ref(false)
const tabList = ref([
    '建设单位', '施工单位', '监理单位', '勘察单位', '设计单位'
])
const activeName = ref('建设单位')
const tableData = ref([])
const updateTableData = (data) => {
    tableData.value = data[activeName.value]
}
const reqTableData = () => {
    isLoading.value = true
    getEnterpriseScale({ scaleType: activeName.value })
        .then(res => {
            updateTableData(res.data)
        }).finally(() => {
            isLoading.value = false
        })
}
const handelTabChange = (name) => {
    activeName.value = name
    reqTableData()
}

const reqData = () => {
    isLoading.value = true
    Promise.all([
        getInfrastructureInvestment(),
        getEnterpriseStructure(),
        getEnterpriseOutputValue(),
        getEnterpriseInfoTotal(),
        getEnterpriseScale({ scaleType: '建设单位' }),
    ]).then((res) => {
        if (res[0].success) {
            updateDataInvestRate(res[0].data)
        }
        if (res[1].success) {
            updateDataEnterpriseCount(res[1].data)
        }
        if (res[2].success) {
            updateDataEnterpriseValue(res[2].data)
        }
        if (res[3].success) {
            updateTotalInfo(res[3].data)
        }
        if (res[4].success) {
            activeName.value = '建设单位'
            updateTableData(res[4].data)
        }
    }).finally(() => {
        isLoading.value = false
    })
}

onMounted(() => {
    // setTimeout(() => {
    //     updateDataInvestRate()
    //     updateDataEnterpriseCount()
    //     updateDataEnterpriseValue()
    //     updateTotalInfo()
    //     handelTabChange('建设单位')
    // }, 1000)
    reqData()
})

</script>

<template>
    <div class="full-wrap">
        <div class="row">
            <div class="panel infrastructure-investment">
                <div class="panel-title">基础设施投资</div>
                <div class="panel-content">
                    <div class="invest-info-list">
                        <div class="inv-info-item" v-for="item in investInfoList" :key="item.title">
                            <img class="icon" :src="item.icon" alt="">
                            <div class="content">
                                <div class="value">{{ item.value }}{{ item.unit }}</div>
                                <div class="title">{{ item.title }}</div>
                            </div>
                        </div>
                    </div>
                    <div class="chart-title">项目投资金额同比</div>
                    <draw-echarts
                        ref="investRateChartBarRef"
                        width="600"
                        height="200"
                        :options="{}"
                    ></draw-echarts>
                </div>
            </div>
            <div class="panel enterprise-parts">
                <div class="panel-title">注册建筑企业结构</div>
                <div class="panel-content">
                    <draw-echarts
                        ref="registeredBuildingEnterpriseStructureChartRef"
                        width="280"
                        height="280"
                        :options="{}"
                    ></draw-echarts>
                    <div class="count-list">
                        <div class="count-list-item" v-for="item in enterpriseCountList" :key="item.name">
                            <span class="name">{{ item.name }}</span>
                            <span class="value" :style="{ color: item.itemStyle.color }">{{ item.value }}家</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="panel enterprise-value">
                <div class="panel-title">注册建筑企业产值</div>
                <div class="panel-content">
                    <draw-echarts
                        ref="enterpriseValueChartBarRef"
                        width="600"
                        height="300"
                        :options="{}"
                    ></draw-echarts>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="panel panel-total">
                <div class="panel-title">项目信息统计</div>
                <div class="panel-content">
                    <div class="total-list-item" v-for="item in totalList" :key="item.name">
                        <div class="value">
                            {{ item.value }}
                            <span class="unit">{{ item.unit }}</span>
                        </div>
                        <div class="name">{{ item.title }}</div>
                    </div>
                </div>
            </div>
            <div class="panel panel-scale">
                <div class="panel-title">企业规模</div>
                <div class="panel-content">
                    <div class="tab-list">
                        <div class="tab-list-item" :class="activeName === item ? 'on' : ''" v-for="item in tabList" @click="handelTabChange(item)">{{ item }}</div>
                    </div>
                    <div class="tab-content table-wrap">
                        <div class="tr th">
                            <span class="td name">企业名称</span>
                            <span class="td">项目数量</span>
                            <span class="td scale">规模（万方）</span>
                            <span class="td cose">造价（亿元）</span>
                        </div>
                        <el-scrollbar style="height: 240px">
                            <div class="list-wrap" ref="listWrap">
                                <div class="tr" :data="item" v-for="(item, index) in tableData" :key="index" >
                                    <div class="td name">
                                        <el-tooltip :content="item.enterpriseName"  placement="top" effect="light">
                                            {{ item.enterpriseName }}
                                        </el-tooltip>
                                    </div>
                                    <div class="td">{{item.projectCount}}</div>
                                    <div class="td scale">{{item.scale}}</div>
                                    <div class="td cose">{{item.cost}}</div>
                                </div>
                                <div class="no-data" v-if="!tableData.length && !isLoading">暂无数据</div>
                                <div class="no-data loading" v-if="isLoading">加载中...</div>
                                <!-- <div class="no-data no-more" v-if="noMore && !isLoading">没有更多</div> -->
                            </div>
                        </el-scrollbar>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.full-wrap {
    height: 100%;
}
.row {
    display: flex;
    justify-content: space-between;
    gap: 20px;
    
    .panel {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        height: 410px;
        margin-bottom: 20px;
        padding: 10px 0 20px 0;
        border: 1px solid;
        border-top: none;
        border-image: linear-gradient(to bottom, rgba(6, 79, 147, 0), #064F93) 1;
        background: linear-gradient(to bottom, #0A143E35, #0A143E);
        .panel-title {  
            height: 32px;
            line-height: 32px;
            text-align: center;
            color: #fff;
            z-index: 1020;
        }
        .panel-content {
        }
    }

    .infrastructure-investment {
        .invest-info-list {
            display: flex;
            margin-top: 20px;
            margin-bottom: 20px;

            .inv-info-item {
                margin-left: 20px;
                margin-right: 20px;
                display: flex;
                align-items: center;
                .icon {
                    width: 70px;
                    height: 70px;
                    object-fit: cover;
                }
                .content {
                    width: 5em;
                    text-align: center;
                    .value {
                        font-weight: bold;
                        color: #F7E004;
                        margin-bottom: 8px;
                    }
                    .title {
                        color: #C7E2FE;
                    }
                }
            }
        }
        .chart-title {
            color: #C7E2FE;
            margin-left: 4%;
        }
    }

    .enterprise-parts {
        .panel-content {
            display: flex;
            margin-top: 50px;
            .count-list {
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                color: #C7E2FE;
                width: 300px;

                .count-list-item {
                    display: flex;
                    padding: 14px 20px;
                    border-top: 1px solid #0086FF;
                    border-bottom: 1px solid #0086FF;
                    background: linear-gradient(#0E245B, #0C3272);
                    .name {
                        display: inline-block;
                        flex: 2;
                    }
                    .value {
                        flex: 1;
                        font-weight: bold;
                    }
                }
            }
        }
    }

    .enterprise-value {
        .panel-content {
            display: flex;
            align-items: flex-end;
        }
    }

    .panel-total {
        flex: 2;
        .panel-content {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-around;
            padding: 20px;
            .total-list-item {
                width: 21%;
                height: 100px;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                margin-top: 20px;
                margin-bottom: 20px;
                text-align: center;
                color: #fff;
                background-image: url('@/assets/imgs/house_rent_bg.png');
                background-size: 100% 100%;
                background-repeat: no-repeat;
                .value {
                    color: #FDE300;
                    font-size: 18px;
                    font-weight: bold;
                    .unit {
                        font-weight: normal;
                        font-size: 13px;
                    }
                }
                .name {
                    width: 5em;
                }
            }
        }
    }
    .panel-scale {
        flex: 3;

        .panel-content {
            padding: 10px 20px 20px 20px;
        }
        .tab-list {
            display: flex;
            gap: 16px;
            .tab-list-item {
                width: 160px;
                height: 32px;
                line-height: 32px;
                text-align: center;
                color: #125B9F;
                border: 1px solid #125B9F;
                cursor: pointer;
            }
            .tab-list-item.on {
                color: #04A7FF;
                border: 1px solid #04A7FF;
            }
        }
        .tab-content {
            margin-top: 16px;
        }
    }

    .table-wrap {
        color: #ffffff;
        
        .tr {
            display: flex;
            height: 40px;
            line-height: 40px;
            .td {
                flex: 2;
                text-overflow: ellipsis;
                overflow: hidden;
                white-space: nowrap;
                word-break: break-all;
                padding: 0 4px;
            }
            .name {
                flex: 4;
            }
            .scale {
                color: #FFE802;
            }
            .cose {
                color: #25F9F2;
            }
        }
        .th {
            color: #06E5FF;
        }
        .tr:nth-child(odd) {
            background-color: #1c2d4c;
        }
        .tr:nth-child(even) {
            background-color: #08142d;
        }

        
        .no-data {
            display: flex;
            justify-content: center;
            align-items: center;
            line-height: 3;
            color: #B9D9F4;
        }
    }
}
</style>